//
//  DigitalView.m
//  GJDigitalSDK
//
//  Created by 吴棒棒 on 2021/10/30.
//

#import "DigitalView.h"
//#import "DigitalMessage.h"
#import "XMPPManager/XMPPManager.h"
#import "OpenUDID-master/OpenUDID.h"
#import "DigitalConfig.h"
#import "ControlPanelView.h"
#import "RequsetUtil.h"

@interface DigitalView ()<XMPPManagerDelegate, DigitalMessageDelegate, RTCVideoViewDelegate, UITextFieldDelegate>
@property (nonatomic, strong) RTCCameraPreviewView *localView;
@property (nonatomic, copy) NSString * contentStr;
@property (nonatomic, strong) ControlPanelView *panelView;
@property (nonatomic, strong) UIButton * openBtn;
@end
@implementation DigitalView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initSource];
    }
    return self;
}
- (void)initSource {
    self.contentStr = @"";
    
    [self initUI];
    [self initXmpp];
    [self initDigital];

}
- (void)initUI {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame =CGRectMake(self.frame.size.width/2.f - 20 , self.frame.size.height - 100, 70, 40);
    [btn setTitle:@"打开" forState:UIControlStateNormal];
    btn.hidden = YES;
    [btn addTarget:self action:@selector(openMenu:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];
    self.openBtn = btn;
    
    RTCCameraPreviewView *localView = [[RTCCameraPreviewView alloc] initWithFrame:CGRectMake(self.frame.size.width - 100, 50, 100, 150)];
    [self addSubview:localView];
    self.localView = localView;
    
    
    
    ControlPanelView *panelView = [[NSBundle bundleForClass:[ControlPanelView class]] loadNibNamed:@"ControlPanelView" owner:nil options:nil].lastObject;
    panelView.frame = CGRectMake(0, self.frame.size.height - 250, self.frame.size.width, 250);
    [self addSubview:panelView];
    self.panelView = panelView;
    __weak typeof(self) weakSelf = self;
    panelView.contentBlock = ^(NSString * _Nonnull content) {
        weakSelf.contentStr = content;
    };
    panelView.sendBlock = ^{
        [weakSelf commandEvent];
    };
    panelView.cancelBlock = ^{
        weakSelf.openBtn.hidden = NO;
    };
    panelView.wavChooseBlock = ^(WAV_ENUM wavType) {
        if (wavType == WAV1_ENUM) {
            [weakSelf commandAudioEvent:@"https://robot.guiji.ai/model/2021/10/21/de44c0d2e92c4845b8d1c6e5b453cd32.wav"];
        }else {
            [weakSelf commandAudioEvent:@"https://robot.guiji.ai/model/2021/11/08/8a96c9d20c5b4074bfa444bcf22eeb07.wav"];
        }
    };
    panelView.longPressBlock = ^(LONG_PRESS_ENUM long_press_type) {
        if (long_press_type == LONG_PRESS_BEGIN) {
            
        }else if (long_press_type == LONG_PRESS_END) {
            RequsetUtil *requestUtil = [[RequsetUtil alloc] init];
            
            [requestUtil upload];
            
            requestUtil.requestDataBlock = ^(NSString * _Nonnull message) {
                [weakSelf sendContent:message];
            };
        }
    };
}
/// 初始化webrtc
- (void)initDigital {
    [DigitalMessage shareMessage].delegate = self;
    [[DigitalMessage shareMessage] initDigital];
}
/// 初始化xmpp
- (void)initXmpp {
    NSString *userName = [DigitalConfig shareConfig].userName;
    NSString *userPassword = [DigitalConfig shareConfig].userPassword;
    NSString *serverIP = [DigitalConfig shareConfig].serverIP;
    [self loginWith:userName pwd:userPassword serverIP:serverIP];
}

//登录页面代理回调用户名和密码
- (void)loginWith:(NSString *)userName pwd:(NSString *)pwd serverIP:(NSString *)ip
{
    //初始化服务器连接管理

    [XMPPManager manager].theHostIP=ip;
    [XMPPManager manager].delegate = self;
    [[XMPPManager manager] setUserName:userName password:pwd];
    BOOL coonect = [[XMPPManager manager] connectServer];
    if (coonect) {
        NSLog(@"连接成功,会话建立");
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(onChatCreate)]) {
            [self.delegate onChatCreate];
        }
    }
    else
    {
        NSLog(@"连接失败");
    }
}
#pragma mark - 事件
- (void)openMenu:(UIButton *)btn {
    self.panelView.hidden = NO;
    btn.hidden = YES;
}
- (void)startEvent {
    /// start事件，客户端发起
    [[XMPPManager manager] toStartMessage];
    /// 心跳包事件
    [[XMPPManager manager] setPingEvent];

}
- (void)commandEvent {
    if (self.contentStr.length == 0) return;

    [self sendContent:self.contentStr];
}

- (void)commandAudioEvent:(NSString *)wavStr {

    [[XMPPManager manager] answerCommandEvent:wavStr isAudio:YES];
}

- (void)asrEvent:(UIButton *)btn {
    btn.selected = !btn.selected;
    [[XMPPManager manager] changeAsrEvent:btn.selected];
}
- (void)sendContent:(NSString *)content {
    if ([[DigitalConfig shareConfig].robotMode isEqualToString:@"bot"]) {
        [[XMPPManager manager] answerCommandEvent:content isAudio:NO];
    }else {
        [[XMPPManager manager] commandEvent:content];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self endEditing:YES];
}



#pragma mark XMPPManager 代理；
//收到消息
- (void)didReceiveMessage:(XMPPMessage *)message
{
    
    if(message==nil)
    {
        return;
    }
    if (message.errorMessage) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(onError:)]) {
            [self.delegate onError:message.errorMessage];
        }
        
        return;
    }
    
    NSString *body = [[message elementForName:@"body"] stringValue];
    NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
    
    if ([message.type isEqualToString:@"chat"]) {
        if(data!=nil)
        {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"didReceiveMessage:%@",dic);
            NSString *eventStr = dic[@"event"];
            
            if (self.delegate && [self.delegate respondsToSelector:@selector(onCustomMsg:)]) {
                [self.delegate onCustomMsg:eventStr];
            }
            
            if ([eventStr isEqualToString:@"render"]) {
                NSDictionary *dataDic = dic[@"data"];
                if (self.delegate && [self.delegate respondsToSelector:@selector(onRender:name:)]) {
                    [self.delegate onRender:dataDic[@"agent"][@"id"]?:@"" name:dataDic[@"agent"][@"name"]?:@""];
                }
                
            }else if([eventStr isEqualToString:@"enterRoom"]) {
                NSDictionary * data_dic=[dic objectForKey:@"data"];
                NSNumber *uuid = dic[@"uuid"];
                [[DigitalMessage shareMessage] onPublisherRemoteJsep:uuid dict:data_dic];
            }else if([eventStr isEqualToString:@"busy"]) {
                if (self.delegate && [self.delegate respondsToSelector:@selector(onBusy)]) {
                    [self.delegate onBusy];
                }
                
            } else if([eventStr isEqualToString:@"command"]) {
                
                
            } else if([eventStr isEqualToString:@"bye"]) {
                if (self.delegate && [self.delegate respondsToSelector:@selector(onByeBye)]) {
                    [self.delegate onByeBye];
                }
                
            } else if([eventStr isEqualToString:@"candidate"]) {
                NSDictionary * data_dic=[dic objectForKey:@"data"];
                
                [[DigitalMessage shareMessage] addCandidate:data_dic[@"candidate"]];
            }else if([eventStr isEqualToString:@"detectedSpeech"]) {
                NSDictionary * data_dic=[dic objectForKey:@"data"];
                
                [self sendContent:data_dic[@"asrText"]?:@""];

            }
            else {
                
            }
        }
        
    }
    
}
//用户登录
- (void)userLoginSuccess:(XMPPJID *)userJID
{
    NSLog(@"用户：%@ 登录成功",userJID.user);
    XMPPPresence *presence = [XMPPPresence presence];
    NSString *toStr = [DigitalConfig shareConfig].userJID;
    [presence addAttributeWithName:@"type" stringValue:@"available"];
    [presence addAttributeWithName:@"to" stringValue:toStr];
    [[XMPPManager manager].xmppStream sendElement:presence];
    
    [self startEvent];
}

//新用户在线
- (void)newUserOnline:(XMPPPresence *)presence
{
    NSString *user = [[presence from] user];
    NSLog(@"发现用户：%@ 上线",user);

}

//用户下线
- (void)hasUserOffline:(XMPPPresence *)presence
{
    NSString *user = [[presence from] user];
    NSLog(@"发现用户：%@ 离线",user);
//    [self onLeaving:0];
}

#pragma mark - DigitalMessageDelegate

- (void)didAddStream:(RTCMediaStream *)stream {
    RTCVideoTrack *remoteVideoTrack = stream.videoTracks[0];
    
    RTCEAGLVideoView *remoteView = [self createRemoteView];
    [remoteVideoTrack addRenderer:remoteView];
    [DigitalMessage shareMessage].localTrack = remoteVideoTrack;
    

    [[XMPPManager manager] clientReadyEvent];
}
/// 发送消息给xmpp
- (void)sendXmppForSdp:(RTCSessionDescription *)sdp {
    [[XMPPManager manager] offerSdp:sdp.sdp];
    
}
- (void)setCaptureSession:(AVCaptureSession *)captureSession {
    self.localView.captureSession = captureSession;

}
- (void)didGenerateIceCandidate:(RTCIceCandidate *)candidate {
    NSDictionary *candidateDic = @{
        @"candidate" : candidate.sdp,
        @"sdpMid" : candidate.sdpMid,
        @"sdpMLineIndex" : @(candidate.sdpMLineIndex),
        @"serverUrl" : candidate.serverUrl
    };
    [[XMPPManager manager] candidateEvent:candidateDic];
}
- (void)didIceConnectionChange:(RTCIceConnectionState)state {
    if (self.delegate && [self.delegate respondsToSelector:@selector(didIceConnectionChange:)]) {
        [self.delegate didIceConnectionChange:state];
    }
}
- (void)onError:(NSError *)error {
    if (self.delegate && [self.delegate respondsToSelector:@selector(onError:)]) {
        [self.delegate onError:error];
    }
}

- (RTCEAGLVideoView *)createRemoteView {

    RTCEAGLVideoView *remoteView = [[RTCEAGLVideoView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    remoteView.contentMode=UIViewContentModeScaleAspectFill;
    remoteView.delegate = self;
    [self addSubview:remoteView];
    [self sendSubviewToBack:remoteView];
    return remoteView;
}
- (void)videoView:(RTCEAGLVideoView *)videoView didChangeVideoSize:(CGSize)size {
//    CGRect rect = videoView.frame;
//    rect.size = size;
//    NSLog(@"========didChangeVideiSize %fx%f", size.width, size.height);
//    videoView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.width/size.width*size.height);
}
@end
